document.addEventListener('DOMContentLoaded', function() {
  console.log('🚀 Popup页面加载完成');
  
  const managePromptsBtn = document.getElementById('managePrompts');
  const scrapePromptsBtn = document.getElementById('scrapePrompts');
  const exportPromptsBtn = document.getElementById('exportPrompts');
  const closeMenuBtn = document.getElementById('closeMenu');
  const minimizeMenuBtn = document.getElementById('minimizeMenu');
  const expandMenuBtn = document.getElementById('expandMenu');
  const floatingMenu = document.getElementById('floatingMenu');

  // 检查元素是否正确获取
  console.log('🔍 检查元素获取状态:');
  console.log('  - closeMenuBtn:', closeMenuBtn);
  console.log('  - floatingMenu:', floatingMenu);

  // 关闭菜单
  if (closeMenuBtn) {
    closeMenuBtn.addEventListener('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      console.log('❌ 关闭按钮被点击');
      
      try {
        // 方法1: 尝试关闭窗口
        if (window.close) {
          window.close();
          console.log('✅ 使用window.close()关闭');
          return;
        }
      } catch (error) {
        console.log('⚠️ window.close()失败:', error);
      }
      
      try {
        // 方法2: 尝试关闭当前标签页
        if (chrome && chrome.tabs) {
          chrome.tabs.getCurrent((tab) => {
            if (tab && tab.id) {
              chrome.tabs.remove(tab.id);
              console.log('✅ 使用chrome.tabs.remove()关闭');
            }
          });
          return;
        }
      } catch (error) {
        console.log('⚠️ chrome.tabs.remove()失败:', error);
      }
      
      // 方法3: 隐藏菜单作为最后手段
      if (floatingMenu) {
        floatingMenu.style.display = 'none';
        console.log('✅ 隐藏菜单作为备用方案');
      }
    });
  } else {
    console.error('❌ 无法找到关闭按钮元素');
  }

  // 缩小菜单
  if (minimizeMenuBtn && floatingMenu) {
    minimizeMenuBtn.addEventListener('click', function() {
      console.log('📉 缩小菜单');
      floatingMenu.classList.add('minimized');
    });
  } else {
    console.error('❌ 无法找到缩小按钮或菜单元素');
  }

  // 展开菜单
  if (expandMenuBtn && floatingMenu) {
    expandMenuBtn.addEventListener('click', function() {
      console.log('📈 展开菜单');
      floatingMenu.classList.remove('minimized');
    });
  } else {
    console.error('❌ 无法找到展开按钮或菜单元素');
  }

  // 提示词管理
  managePromptsBtn.addEventListener('click', function() {
    chrome.tabs.create({ url: chrome.runtime.getURL('manage.html') });
    window.close();
  });

  // 爬取提示词
  scrapePromptsBtn.addEventListener('click', function() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {action: 'scrapePrompts'}, function(response) {
        if (response && response.success) {
          showToast('提示词爬取成功！', 'success');
          setTimeout(() => {
            window.close();
          }, 1500);
        } else {
          showToast('爬取失败：' + (response ? response.error : '未知错误'), 'error');
          setTimeout(() => {
            window.close();
          }, 2000);
        }
      });
    });
  });

  // 导出Excel
  exportPromptsBtn.addEventListener('click', function() {
    chrome.storage.local.get(['prompts'], function(result) {
      const prompts = result.prompts || [];
      if (prompts.length === 0) {
        alert('没有可导出的提示词数据');
        return;
      }
      
      // 创建Excel数据
      const csvContent = createCSV(prompts);
      downloadCSV(csvContent, 'prompts.csv');
      window.close();
    });
  });

  // 创建CSV内容
  function createCSV(prompts) {
    const headers = ['image', 'prompt'];
    const rows = prompts.map(prompt => [
      prompt.image || '',
      (prompt.text || '').replace(/"/g, '""') // 转义双引号
    ]);
    
    const csvRows = [headers, ...rows].map(row => 
      row.map(field => `"${field}"`).join(',')
    );
    
    return csvRows.join('\n');
  }

  // 下载CSV文件
  function downloadCSV(content, filename) {
    const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  // 显示Toast提示
  function showToast(message, type = 'info') {
    // 移除已存在的toast
    const existingToast = document.querySelector('.toast');
    if (existingToast) {
      existingToast.remove();
    }

    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    
    // 根据类型设置样式
    if (type === 'success') {
      toast.style.background = '#4caf50';
    } else if (type === 'error') {
      toast.style.background = '#f44336';
    } else {
      toast.style.background = '#2196f3';
    }
    
    toast.style.cssText += `
      position: fixed;
      top: 20px;
      left: 50%;
      transform: translateX(-50%);
      background: ${toast.style.background};
      color: white;
      padding: 12px 24px;
      border-radius: 6px;
      z-index: 10000;
      font-size: 14px;
      font-weight: 500;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      opacity: 0;
      transition: opacity 0.3s ease-in-out;
    `;
    
    document.body.appendChild(toast);
    
    // 淡入效果
    setTimeout(() => {
      toast.style.opacity = '1';
    }, 10);
    
    // 自动消失
    setTimeout(() => {
      toast.style.opacity = '0';
      setTimeout(() => {
        if (toast.parentNode) {
          toast.parentNode.removeChild(toast);
        }
      }, 300);
    }, 2000);
  }
});
